<template>
  <van-search v-model="insearch" show-action placeholder="学校/地址/商务楼">
    <template #action>
      <div @click="onSearch">搜索</div>
    </template>
  </van-search>
  <van-cell-group title="搜索结果" v-if="addresslist">
    <template v-for="(item, index) of addresslist" :key="index">
      <van-cell
        :title="item.name"
        :label="item.address"
        @click="handleResult(item)"
      ></van-cell>
    </template>
  </van-cell-group>
  <template v-if="history && !addresslist">
    <div>
      <van-tag
        v-for="(item,index) of history"
        :show="tagShow !== index"
        :key="item"
        :style="{ margin: '10px 10px 0 10px' }"
        type="primary"
        plain
        closeable
        @close="removeHistory(index)"
        >{{ item.name }}</van-tag
      >
    </div>
  </template>
  <van-empty
    v-if="!history && addresslist == ''"
    description="没有找到搜索结果"
  />
</template>

<script lang="ts">
import { computed, defineComponent, getCurrentInstance, Ref, ref } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

export default defineComponent({
  setup() {
    const store = useStore();
    const router = useRouter();
    const insearch = ref(null);
    const addresslist: Ref = ref(null);
    const tagShow: Ref = ref(null)
    const { proxy }: any = getCurrentInstance();
    const history = computed(() => store.getters.addressHistory);
    const onSearch = () => {
      let cityid = store.getters.cityId;
      if (!insearch.value) {
        addresslist.value = "";
        proxy.$toast("请输入内容");
      } else {
        proxy.axios
          .get(`/v1/pois?city_id=${cityid}&keyword=${insearch.value}`)
          .then((res: any) => {
            addresslist.value = res;
          });
      }
    };
    const removeHistory = (idx:number) => {
      tagShow.value = idx
    }
    const handleResult = (v: any) => {
      store.dispatch("SaveAdrHistory", v).then(() => {
        router.push({ path: "/home", query:{ lat: v.latitude, lng: v.longitude, cityname: v.name } })
      });
    };
    return {
      insearch,
      onSearch,
      addresslist,
      handleResult,
      history,
      tagShow,
      removeHistory
    };
  },
});
</script>

<style scoped>
</style>